﻿using fastJSON;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace SX.Utils
{
    public static class AuthHelper
    {
        //private static JSONParameters Parameter;
        //static AuthHelper() {
        //    Parameter = new JSONParameters { EnableAnonymousTypes = true, UseFastGuid = true, SerializeNullValues = false, DateTimeMilliseconds = true, UseUTCDateTime = false };
        //}
        public static void SignIn<T>(string loginName, T userData)
        {
            var data = JsonHelper.ToJson(userData );
            //data = data.GZip();
            //创建一个FormsAuthenticationTicket，它包含登录名以及额外的用户数据。
            var ticket = new FormsAuthenticationTicket(2,
                loginName, DateTime.Now, DateTime.Now.Add( FormsAuthentication.Timeout), false, data);

            //加密Ticket，变成一个加密的字符串。
            var cookieValue = FormsAuthentication.Encrypt(ticket);

            //根据加密结果创建登录Cookie
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
            {
                HttpOnly = true,
                Secure = FormsAuthentication.RequireSSL,
                Domain = FormsAuthentication.CookieDomain,
                Path = FormsAuthentication.FormsCookiePath,
                Expires = DateTime.Now.AddDays(4),
            };
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }
            //if (expireMin > 0)
            //    cookie.Expires = DateTime.Now.AddMinutes(expireMin);

            var context = HttpContext.Current;
            if (context == null)
                throw new InvalidOperationException();

            //写登录Cookie
            context.Response.Cookies.Remove(cookie.Name);
            context.Response.Cookies.Add(cookie);
            if (context.Request.Cookies.AllKeys.Contains(cookie.Name))
            {
                context.Request.Cookies.Remove(cookie.Name);
            }
            context.Request.Cookies.Add(cookie);
        }

        public static void SingOut()
        {
            FormsAuthentication.SignOut();
        }
  
        public static T GetUserData<T>() where T : class, new()
        {
            T UserData = null;
            try
            {
                var context = HttpContext.Current;
                var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                UserData = JsonHelper.ToObject<T>( ticket.UserData);
            }
            catch
            { }

            return UserData;
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        /// <returns></returns>
        public static bool IsAuth() {
            return HttpContext.Current.Request.IsAuthenticated;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string GetName() {
            string name = "";
            try
            {
                var context = HttpContext.Current;
                var cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
                name = ticket.Name;
            }
            catch
            { } 
            return name; 
        }

        /// <summary>
        /// 登录Url
        /// </summary>
        public static string LoginUrl {
            get {
                return FormsAuthentication.LoginUrl;
            }
        }
    }
}
